import os
import glob

root = os.path.dirname(os.path.abspath(__file__))

def fix_file_encoding(file_path):
    """检查并修复文件编码"""
    try:
        # 尝试用UTF-8读取
        with open(file_path, 'r', encoding='utf-8') as f:
            content = f.read()
            print(f"UTF-8: {file_path}")
            return True
    except UnicodeDecodeError:
        # 尝试用GBK读取
        try:
            with open(file_path, 'r', encoding='gbk') as f:
                content = f.read()
            # 用UTF-8重新写入
            with open(file_path, 'w', encoding='utf-8') as f:
                f.write(content)
            print(f"GBK->UTF-8: {file_path}")
            return True
        except:
            # 其他编码，尝试二进制模式读取后跳过控制字符
            try:
                with open(file_path, 'rb') as f:
                    content = f.read()
                # 尝试解码并重新编码
                for enc in ['latin1', 'cp1252']:
                    try:
                        decoded = content.decode(enc)
                        with open(file_path, 'w', encoding='utf-8') as f:
                            f.write(decoded)
                        print(f"{enc}->UTF-8: {file_path}")
                        return True
                    except:
                        continue
                print(f"Binary mode: {file_path} (could not decode)")
                return False
            except Exception as e:
                print(f"Error: {file_path} - {e}")
                return False
    except Exception as e:
        print(f"Error: {file_path} - {e}")
        return False

def fix_directory_encodings(directory):
    """修复目录中所有文件的编码"""
    # 查找所有文件
    all_files = []
    for pattern in ["**/*.sh", "**/*.bat", "**/*.py", "**/*.md", "**/*.yml", "**/*.yaml", "**/*.xml", "**/*.java", "**/*.properties"]:
        all_files.extend(glob.glob(os.path.join(directory, pattern), recursive=True))
    
    fixed_count = 0
    total_count = len(all_files)
    
    for file_path in all_files:
        if os.path.isfile(file_path):
            if fix_file_encoding(file_path):
                fixed_count += 1
    
    print(f"\nSummary:")
    print(f"Total files: {total_count}")
    print(f"Fixed files: {fixed_count}")

if __name__ == "__main__":
    print("Checking and fixing file encodings...")
    # 修复scripts目录
    fix_directory_encodings(root)
    print("\n✅ Encoding fix complete!")